/**  
 * All rights Reserved, Designed By <a href="www.itttq.com" target="_blank">www.itttq.com</a>
 * @date:   2017-07-21 11:42:21
 * @Copyright: 2017 <a href="www.itttq.com" target="_blank">www.itttq.com</a> Inc. All rights reserved. 
 */
package com.itttq.gshop.h5.controller.user;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.itttq.gshop.domain.po.UserAddressPo;
import com.itttq.gshop.domain.po.UserInfoPo;
import com.itttq.gshop.domain.to.ResultTo;
import com.itttq.gshop.generic.cmpt.annotation.Auth;
import com.itttq.gshop.generic.connector.IUserAddressConnector;
import com.itttq.gshop.generic.controller.GenericController;
@Auth
@RestController
@RequestMapping("address")
public class AddressController extends GenericController {
	private static final long serialVersionUID = -6485775841311449L;
	public static final String cacheKey = "userAddress";
	@Autowired
	private IUserAddressConnector userAddressConnector;
	/**
	 * 获取当前登录用户的所有收货地址
	 * 
	 * @param request
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("list.html")
    public ModelAndView getAddresses(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/mine/address");
		UserInfoPo user = this.getUserFromSession(request);
		UserAddressPo userAddress = new UserAddressPo();
		userAddress.setUserId(user.getId());
		userAddress.setSize(999);
		mv.addObject("addrs", userAddressConnector.getUserAddresss(userAddress).getData());
        return mv;
    }
	
	/**
	 * 添加地址
	 * 
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("add.html")
	public ModelAndView addAddress() {
		return new ModelAndView("/mine/address-edit");
	}
	/**
	 * 根据ID获取地址
	 * 
	 * @param id
	 * @Author 迷蝶
	 * @return ModelAndView
	 */
	@RequestMapping("edit/{id}.html")
	public ModelAndView getUserAddress(@PathVariable("id") int id) {
		ModelAndView mv = addAddress();
		mv.addObject("addr", userAddressConnector.getUserAddress(id));
		return mv;
	}
	/**
	 * 保存收货地址，有ID则更新数据，没有则新建数据
	 * 
	 * @param addr
	 * @Author 迷蝶
	 * @return Integer
	 */
	@RequestMapping("save.html")
	public ResultTo saveUserAddress(UserAddressPo addr, HttpServletRequest request) {
		ResultTo rt = new ResultTo();
		UserInfoPo user = this.getUserFromSession(request);
		addr.setUserId(user.getId());
		addr.setUserName(user.getUsername());
		if(userAddressConnector.saveUserAddress(addr) < 0) {
			rt.setCode(ResultTo.FAIL);
		}
		return rt;
	}

	@RequestMapping("del/{id:^[0-9]*$}")
	public Integer delUserAddress(@PathVariable("id") int id) {
		return userAddressConnector.delUserAddress(id);
	}
}